//
//  DHChatToolView.m
//  YDAPP
//
//  Created by tyxd on 17/1/3.
//  Copyright © 2017年 TYXD. All rights reserved.
//

#import "DHChatToolView.h"

@interface DHChatToolView()<UITextViewDelegate,UIScrollViewDelegate>
{
    //键盘高度
    CGFloat keyHeight;
    
    //记录一开始的frame
    CGRect _startfFrame;
    
    UIScrollView *emojeS;
    
    UIButton * emojeBut;
}

@property(nonatomic,strong)NSMutableArray *faceArrM;

@end

@implementation DHChatToolView

#pragma mark  -- 重写set方法

-(void)msgTextFrame
{
    if (self.faceBtn.hidden == NO  && self.sendBtn.hidden == NO &&  self.talkBtn.hidden == YES) {
        
        _msgTextView.frame = CGRectMake(10, 5, _startfFrame.size.width - 10  - 49 * 2, _startfFrame.size.height - 10);
        
    }else if (self.faceBtn.hidden == NO  && self.sendBtn.hidden == NO &&  self.talkBtn.hidden == NO)
    {
        
        _msgTextView.frame = CGRectMake(49, 5, _startfFrame.size.width - 49 * 3, _startfFrame.size.height - 10);
        
    }else if (self.faceBtn.hidden == YES  && self.sendBtn.hidden == NO &&  self.talkBtn.hidden == NO)
    {
        
        _msgTextView.frame = CGRectMake(49, 5, _startfFrame.size.width   - 49 * 2, _startfFrame.size.height - 10);
        
    }
    else if (self.faceBtn.hidden == YES  && self.sendBtn.hidden == NO &&  self.talkBtn.hidden == YES)
    {
        
        _msgTextView.frame = CGRectMake(10, 5, _startfFrame.size.width - 10  - 49, _startfFrame.size.height - 10);
        
    }else if (self.faceBtn.hidden == NO  && self.sendBtn.hidden == YES &&  self.talkBtn.hidden == NO)
    {
        
        _msgTextView.frame = CGRectMake(49, 5, _startfFrame.size.width   - 49 * 2, _startfFrame.size.height - 10);
        
        
    }
    else if (self.faceBtn.hidden == YES  && self.sendBtn.hidden == YES &&  self.talkBtn.hidden == YES)
    {
        
        _msgTextView.frame = CGRectMake(10, 5, _startfFrame.size.width   - 10 * 2, _startfFrame.size.height - 10);
        
        
    }else if (self.faceBtn.hidden == YES  && self.sendBtn.hidden == YES &&  self.talkBtn.hidden == NO)
    {
        
        _msgTextView.frame = CGRectMake(49, 5, _startfFrame.size.width   - 10 - 49, _startfFrame.size.height - 10);
        
        
    }
    else if (self.faceBtn.hidden == NO  && self.sendBtn.hidden == YES &&  self.talkBtn.hidden == YES)
    {
        
        _msgTextView.frame = CGRectMake(10, 5, _startfFrame.size.width   - 10 - 49, _startfFrame.size.height - 10);
        
        
    }
    
    
    
    _faceBtn.frame = CGRectMake(CGRectGetMaxX(self.msgTextView.frame) , 0, 49, 49);

}

-(void)setIsHidFaceBtn:(BOOL )isHidFaceBtn
{
    _isHidFaceBtn = isHidFaceBtn;
    
    self.faceBtn.hidden = isHidFaceBtn;
    
    [self msgTextFrame];
    
}

-(void)setIsHidSendBtn:(BOOL )isHidSendBtn
{
    _isHidSendBtn = isHidSendBtn;
    
    self.sendBtn.hidden = isHidSendBtn;
    
    [self msgTextFrame];
    
}

-(void)setIsHidVoiceBtn:(BOOL )isHidVoiceBtn
{
    _isHidVoiceBtn = isHidVoiceBtn;
    
    self.talkBtn.hidden = isHidVoiceBtn;
    
    [self msgTextFrame];
    
}

#pragma mark -- 懒加载

-(NSMutableArray *)faceArrM
{
    if (!_faceArrM) {
        
        _faceArrM = [NSMutableArray array];
        
    }
    
    return _faceArrM;
    
}

-(UIView *)enjoyView
{
    if (!_enjoyView) {
        
//        UIView *enjoyView = [UIView alloc]
        
        //表情
        //获取默认表情数组
        [self.faceArrM removeAllObjects];
        for (int i=0x1F600; i<=0x1F64F; i++) {
            if (i < 0x1F641 || i > 0x1F644) {
                int sym = EMOJI_CODE_TO_SYMBOL(i);
                NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding];
                [self.faceArrM addObject:emoT];
            }
        }
//        [self.faceArrM insertObject:@"" atIndex:27];
//        [self.faceArrM insertObject:@"" atIndex:55];
        NSInteger pageCount;
        
        if (self.faceArrM.count%28 == 0) {
            pageCount = self.faceArrM.count/28;
        }else{
            pageCount = self.faceArrM.count/28 +1 ;
        }
        
        UIView *enjoyView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight/3*2-10, kScreenWidth, kScreenHeight/3 + 10)];
        
        enjoyView.backgroundColor =  BackGroundColor;
        enjoyView.hidden = YES;
        [[Helper view:self].view addSubview:enjoyView];
        
        emojeS = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight/3 )];
        emojeS.contentSize = CGSizeMake(kScreenWidth*pageCount, 0);
        emojeS.pagingEnabled = YES;
        emojeS.delegate = self;
        //设置水平滑动条是否显示
        emojeS.showsHorizontalScrollIndicator = NO;
        emojeS.bounces = NO;
        [enjoyView addSubview:emojeS];
        //emoj图
        
        for (int i = 0; i<pageCount; i++) {
            UIView *emojV = [[UIView alloc]initWithFrame:CGRectMake(i * kScreenWidth, 0, kScreenWidth, kScreenHeight/3 )];
            
            emojV.backgroundColor = BackGroundColor
            ;
            [emojeS addSubview:emojV];
            
            for (int j = 0; j< 28; j++) {
                emojeBut = [UIButton buttonWithType:UIButtonTypeCustom];
                emojeBut.frame = CGRectMake(j%7*kScreenWidth/7, j/7 * kScreenHeight/12, kScreenWidth/7, kScreenHeight/12);
                
                if (28*i + j <self.faceArrM.count) {
                    [emojeBut setTitle:[NSString stringWithFormat:@"%@",self.faceArrM[28*i + j]] forState:UIControlStateNormal];
                }
                if (28*i+j == 28 *(i +1) - 1) {
                    [emojeBut setImage:[UIImage imageNamed:@"faceDelete"] forState:UIControlStateNormal];
                    [emojeBut setTitle:@"" forState:UIControlStateNormal];
                }
                [emojeBut addTarget:self action:@selector(showEmoje:) forControlEvents:UIControlEventTouchUpInside];
                emojeBut.tag = 100 + 28*i+j;
                [emojV addSubview:emojeBut];
            }
        }
        //page页
        UIPageControl *page1 = [[UIPageControl alloc] initWithFrame:CGRectMake(0,enjoyView.frame.size.height - 10, kScreenWidth, 10)];
        //设置页数
        page1.numberOfPages = pageCount;
        page1.backgroundColor = BackGroundColor;
        page1.tag = 1002;
        //未走的颜色
        page1.pageIndicatorTintColor = [UIColor whiteColor];
        //当前page的颜色
        page1.currentPageIndicatorTintColor = [UIColor darkGrayColor];
        [enjoyView addSubview:page1];
        
        _enjoyView = enjoyView;
        
    }

        
        
    return _enjoyView;
}

-(UITextView *)msgTextView
{
    if (!_msgTextView) {
        //消息框
        UITextView *text = [[UITextView alloc]initWithFrame:CGRectMake(49, 5, kScreenWidth -147, self.frame.size.height - 10)];
        text.layer.cornerRadius = 5;
        text.clipsToBounds = YES;
        text.layer.borderWidth = 1.0;
        text.layer.borderColor = BackGroundColor.CGColor;
        
        text.delegate = self;
        
        //设置字体
        _msgTextView = text;
        [self addSubview:text];
    }
    return _msgTextView;
}

-(UIButton *)longtalkBtn
{
    if (!_longtalkBtn) {
        //长按说话
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(49, 5, kScreenWidth -147, 39);
        btn.layer.borderWidth = 1.0;
        btn.layer.borderColor = BackGroundColor.CGColor;
        btn.layer.cornerRadius = 5;
        btn.clipsToBounds = YES;
        [btn setTitle:@"按住说话" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        btn.hidden = YES;
        _longtalkBtn = btn;
        [self addSubview:btn];
    }
    return _longtalkBtn;
}

-(UIButton *)talkBtn
{
    if (!_talkBtn) {
        //说话
        UIButton *talkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        talkBtn.frame = CGRectMake(0, 0, 49, 49);
        talkBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [talkBtn setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
        [talkBtn setImage:[UIImage imageNamed:@"键盘"] forState:UIControlStateSelected];
        _talkBtn = talkBtn;
        [self addSubview:talkBtn];
    }
    return _talkBtn;
}

-(UIButton *)faceBtn
{
    if (!_faceBtn) {
        UIButton *facrBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        facrBtn.frame = CGRectMake(CGRectGetMaxX(self.msgTextView.frame) , 0, 49, 49);
        facrBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [facrBtn setImage:[UIImage imageNamed:@"发送表情"] forState:UIControlStateNormal];
        [facrBtn addTarget:self action:@selector(hidFaceView:) forControlEvents:UIControlEventTouchUpInside];
        
        _faceBtn = facrBtn;
        [self addSubview:facrBtn];
    }
    return _faceBtn;
}

//更多
-(UIButton *)addBtn
{
    if (!_addBtn) {
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        addBtn.frame = CGRectMake(CGRectGetMaxX(self.msgTextView.frame) + 44, 0, 49, 49);
        addBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [addBtn setImage:[UIImage imageNamed:@"加号发送多媒体"] forState:UIControlStateNormal];
        [self addSubview:addBtn];
        _addBtn = addBtn;
    }
    return _addBtn;
}

//发送
-(UIButton *)sendBtn
{
    if (!_sendBtn) {
        //发送
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(CGRectGetMaxX(_faceBtn.frame), 7, 45, 35);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn setTitleColor:BlackColor];
//        sendBtn.backgroundColor = kNavBackGroudColor;
        sendBtn.layer.cornerRadius= 5;
        sendBtn.clipsToBounds = YES;
        sendBtn.hidden = YES;
        [sendBtn addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
        _sendBtn = sendBtn;
        [self addSubview:sendBtn];
    }
    return _sendBtn;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [IQKeyboardManager sharedManager].enable = NO;
        
        //增加监听，当键盘出现或改变时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        
        //增加监听，当键退出时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
        

        _startfFrame = frame;
    }
    return self;
}

#pragma mark UITextViewDelegate

//要实现的Delegate方法,键盘发送
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        
        
        [self send];
        
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}



//当textView的内容发生改变的时候调用
-(void)textViewDidChange:(UITextView *)textView
{
    [self changeFrame];
    
    
}

-(void)changeFrame
{
    CGFloat sizeHeight = [self.msgTextView.text boundingRectWithSize:CGSizeMake(_msgTextView.frame.size.width - 5, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size.height;
    
    CGFloat height = sizeHeight + 10;
    
    CGRect frame = _startfFrame;
    
    //距离屏幕底部的高度
    CGFloat toolHeight = 0;
    if (_enjoyView.hidden == YES) {
        
        toolHeight = keyHeight;
        
    }else
    {
        toolHeight = _enjoyView.size.height;
    }
    
    
    if (sizeHeight > 30 && sizeHeight <  80) {
        frame.origin.y = kScreenHeight - toolHeight -height - 10 -65;
        frame.size.height = height + 10;
        self.frame = frame;
    }
    else if (sizeHeight >= 80)
    {
        
        frame.origin.y = kScreenHeight - toolHeight - 90  - 10 - 65;
        frame.size.height = 100;
        self.frame = frame;
//        self.frame = CGRectMake(10 , kScreenHeight - keyHeight - 80 - 10, width, 80);
    }else
    {
        
        frame.origin.y = kScreenHeight - toolHeight  - _startfFrame.size.height - 65;
        self.frame = frame;
        
        
//        self.frame = CGRectMake(10 , kScreenHeight - keyHeight - 40 , width, 30);
    }
    
    CGRect msgFrame = _msgTextView.frame;
    
    msgFrame.size.height = self.frame.size.height - 10;
    
    _msgTextView.frame = msgFrame;
    
    
    if (self.msgTextView.text.length == 0) {
//        self.msgTextView.placeLable.hidden = NO;
    }else
    {
//        self.msgTextView.placeLable.hidden = YES;
    }
}

#pragma mark  -- click 

-(void)showEmoje:(UIButton *)sender
{
    
    
    if ((sender.tag  - 100 +1)%28 == 0 ) {
        
        if (self.msgTextView.text.length>=2) {
            self.msgTextView.text = [self.msgTextView.text substringToIndex:self.msgTextView.text.length-2];
        }
    }else
    {
        if (sender.tag -100 < self.faceArrM.count) {
            self.msgTextView.text = [NSString stringWithFormat:@"%@%@",self.msgTextView.text,self.faceArrM[sender.tag - 100]];
        }
    }
    if (self.msgTextView.text.length >0) {
        
        
        
    }else
    {
        
    }
    
    [self textViewDidChange:self.msgTextView];
    
}

//隐藏表情
-(void)hidFaceView
{
    self.enjoyView.hidden = YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.frame =  _startfFrame;
        
    }];
    
}

-(void)hidFaceView:(UIButton *)sender
{
    
    
    self.enjoyView.hidden = ! self.enjoyView.hidden;
    
    [[Helper view:self].view endEditing:YES];
    
    [[Helper view:self].view bringSubviewToFront:self];
    
    
    
    
    if (self.enjoyView.hidden == NO) {
        
        [self changeFrame];
        
        
        
    }else
    {
        
        [_msgTextView becomeFirstResponder];
    }

}

-(void)send
{
    if (_msgTextView.text.length == 0) {
        
        
        [MBProgressHUD showText:@"您还没有输入内容"];
        
        return ;
    }
    
    //在这里做你响应return键的代码
    //完成
    
    if (_delegate && [_delegate respondsToSelector:@selector(chatToolViewClickSend)]) {
        [_delegate chatToolViewClickSend];
    }

}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
    self.enjoyView.hidden = YES;
    
    [[Helper view:self].view bringSubviewToFront:self];
    
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    [UIView animateWithDuration:0.5 animations:^{
        [self changeFrame];
    }];
    
    
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.frame = _startfFrame;
    }];
}


#pragma mark -- UIScrollViewDelegate


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    

    if (scrollView == emojeS ) {
        //取到page
        UIPageControl *page1 = (UIPageControl *)[_enjoyView viewWithTag:1002];
        //取到当前页数
        int index = scrollView.contentOffset.x / kScreenWidth;
        //设置当前page的页数为index
        page1.currentPage = index;
    }
    
}

- (void)dealloc
{
    [IQKeyboardManager sharedManager].enable = YES;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

@end
